package 链表;

public class LinkList implements IList{
    private Node head;//指向头节点
    private Node current;//当前节点位置，用于循环遍历
    private int size;//单链表长度
    //构造空表
    public LinkList(){
        head = current=new Node(null);
        size=0;
    }
    //indec(i),用于将当前节点current指向链表的第i个节点
    private void index(int i) throws Exception {
        if(i<-1 ||i>size-1){
            throw new Exception("参数错误");
        }
        if(i==-1){
            current=head;
        }else {
            current = head.next;
            int j=0;
            while(current!=null && j<i){
                current=current.next;
                j++;
            }
        }
    }
    @Override
    public void insert(int i, Object obj) throws Exception {
        if(i<0 || i>size){
            throw new Exception("参数错误");
        }
        index(i-1);
        Node a = new Node(obj,null);
        a.next = current.next;
        current.next = a;
        size++;
    }

    @Override
    public Object delete(int i) throws Exception {
        if(size==0){
            throw new Exception("链表空");
        }
        if(i<0 || i>size){
            throw new Exception("参数错误");
        }
        index(i-1);
        Object obj  = current.next.data;
        current.next = current.next.next;
        size--;
        return obj;
    }

    @Override
    public Object getData(int i) throws Exception {
        index(i);
        return current.data;
    }

    @Override
    //用值找位置，首节点为0，头节点为-1,找不到返回-2
    public int locateData(Object obj) throws Exception {
        current=head.next;
        if(current==null){
            return  -1;
        }
        int j=0;
        while(current!=null && current.data!=obj){
            current = current.next;//指向下一个节点
            j++;
        }
        if(j<size){
            return j;
        }
        return -2;
    }

    @Override
    public void print() throws Exception {
        current=head.next;//指向头结点的下一个
        while(current!=null){
            System.out.println(current.data+"");//输出当前节点的数据
            current =  current.next;
        }
        System.out.println();
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    public void append(Object obj) throws Exception{
        Node p = new Node(obj,null);
        if(head.next!=null){
            current.next=p;
        }else{
            head.next=p;

        }
        current=p;
        size++;
    }
}
